package com.me.service;

import com.me.pojo.FileMail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;

@Service
public class SendMailService {

    @Autowired
    JavaMailSenderImpl mailSender;

    @Async
    public void sendMail(String subject, String text, String to, String from) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(text);

        simpleMailMessage.setTo(to);
        simpleMailMessage.setFrom(from);
        mailSender.send(simpleMailMessage);
    }

    @Async
    public void sendMailFile(FileMail file) {
        // 一个复杂的邮件
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        // 组装
        MimeMessageHelper helper = null; /// true 表示支持多文件 false 表示不支持多文件
        try {
            helper = new MimeMessageHelper(mimeMessage,true);
            // 正文
            helper.setSubject(file.getSubject()); // 标题
            helper.setText(file.getText(),true); // 内容 true表示可以识别html false表示不能识别

            // 附件
            helper.addAttachment(file.getFile().getOriginalFilename(),file.getFile());

            helper.setTo(file.getTo()); // 接受者的邮箱
            helper.setFrom(file.getFrom()); // 发送者的邮箱
            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }

}
